<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="state.dialogTitle"
    :width="width"
    draggable
  >
    <el-form
      ref="dataFormRef"
      v-loading="state.loading"
      :model="form"
      :rules="dataRules"
      label-width="80px"
      :disabled="state.operType === 'view'"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="名称" prop="functionName">
            <el-input
              v-model="form.functionName"
              placeholder="请输入函数名称"
              length="32"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <DictSelect
              v-model:defaultValue="form.status"
              dict-code="1022"
              showAll="N"
              expanding
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="类名" prop="className">
            <el-input v-model="form.className" type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="参数" prop="functionParams">
            <div>
              <div>
                <el-text style="margin-right: 20px">参数名</el-text>
                <el-input
                  v-model="paramsItem.paramName"
                  type="text"
                  style="width: 150px"
                />
                <el-text style="margin-left: 20px; margin-right: 20px"
                  >参数描述</el-text
                ><el-input
                  v-model="paramsItem.paramLabel"
                  type="text"
                  style="width: 150px; margin-right: 20px"
                />
                <el-button type="primary" @click="handleAddParam"
                  >新增</el-button
                >
              </div>
              <div style="display: block">
                <el-tag
                  type="primary"
                  v-for="(item, index) in form.params"
                  :key="index"
                  closable
                  hit
                  @close="handleDeleteParam(index)"
                  style="margin-right: 20px"
                >
                  `{{ item.paramName }}:{{ item.paramLabel }}`
                </el-tag>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="remark" label="备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template v-if="state.operType !== 'view'" #footer>
      <span class="dialog-footer">
        <el-button type="warning" @click="close">{{
          translate("buttons.cancel")
        }}</el-button>
        <el-button type="primary" :disabled="state.loading" @click="onSubmit">
          {{ translate("buttons.confirm") }}</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="RuleFunctionEdit">
import { useMessage } from "@/hooks/message";
import { addObj, updateObj } from "@/api/flow/rulefunction";
import { ref } from "vue";
import { translate } from "@/plugins/i18n";
import DictSelect from "@/components/dictSelect.vue";

const props = defineProps({
  title: {
    type: String,
    default: "动态处理人函数"
  },
  width: {
    type: String,
    default: "60%"
  },
  model: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(["refresh"]);

// 定义变量内容
const dataFormRef = ref();
const state = reactive({
  dialogTitle: props.title,
  dialogVisible: false,
  loading: false,
  operType: false
});
const paramsItem = reactive({
  paramName: "",
  paramLabel: ""
});

// 提交表单数据
const form = reactive({
  id: "",
  functionName: "",
  className: "",
  functionParams: "",
  params: [],
  status: "0",
  remark: ""
});

// 定义校验规则
const dataRules = ref({
  functionName: [
    {
      required: true,
      message: "名称不能为空",
      trigger: "blur"
    }
  ],
  className: [{ required: true, message: "函数类名不能为空", trigger: "blur" }],
  status: [{ required: true, message: "状态不能为空", trigger: "blur" }]
});

onMounted(() => {});

const handleAddParam = () => {
  form.params.push({
    paramName: paramsItem.paramName,
    paramLabel: paramsItem.paramLabel
  });
  paramsItem.paramName = "";
  paramsItem.paramLabel = "";
};

const handleDeleteParam = index => {
  form.params.splice(index, 1);
};

// 打开弹窗
const show = (type, row) => {
  state.dialogVisible = true;
  state.operType = type;
  form.id = "";
  if (type === "add") {
    state.dialogTitle = `新增${props.title}`;
  } else if (type === "edit") {
    state.dialogTitle = `修改${props.title}`;
  } else if (type === "view") {
    state.dialogTitle = `查看${props.title}`;
  }
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });
  if (row.id) {
    form.id = row.id;
    form.functionName = row.functionName;
    form.className = row.className;
    form.functionParams = row.functionParams;
    form.params = row.params;
    form.status = row.status;
    form.remark = row.remark;
    if (!form.params) {
      form.params = [];
    }
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().then(valid => {
    if (!valid) return false;
    state.loading = true;
    if (form.id) {
      const params = {
        id: form.id,
        functionName: form.functionName,
        className: form.className,
        functionParams: JSON.stringify(form.params),
        status: form.status,
        remark: form.remark
      };
      updateObj(params).then(res => {
        if (res.code === 200) {
          useMessage().success("保存成功");
          emit("refresh");
          close();
        } else {
          useMessage().error(res.msg);
        }
      });
    } else {
      addObj(params).then(res => {
        if (res.code === 200) {
          useMessage().success("保存成功");
          emit("refresh");
          close();
        } else {
          useMessage().error(res.msg);
        }
      });
    }
  });
  state.loading = false;
};

const close = () => {
  state.dialogTitle = props.title;
  dataFormRef.value?.resetFields();
  state.dialogVisible = false;
};

// 暴露变量
defineExpose({
  show,
  close
});
</script>
